import { useDicts } from '@/layout/hooks/useDictOptions';
import editForm from "./form.vue";
import feedback from "@/utils/feedback";
import { usePublicHooks } from "@/views/hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, toRaw, watch } from "vue";
import type { FormItemProps } from "./types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import { treeselect, } from '@/api/system/menu';
import { CategoryListTree } from "@/api/pms/catogory";
//api
import {
    AttrDelete,
    AttrList,
    AttrAdd,
    AttrEdit,
    AttrDetail
} from "@/api/pms/attr";
import { useDetail } from '@/utils/route';

export function useHook() {
    const { getParameter } = useDetail();
    //表单查询字段
    const form = reactive({

        attrName: null,

        attrType: null,
        groupId: null,
        enable: null,

        cId: null,
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const categotyList = ref([]);

    //查询字典 格式: type1,type2 返回 optionsData.type1 ptionsData.type2
    const { optionsData } = useDicts<any>("sys_yes_no, sys_common_status")


    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });
    //表格字段
    const columns: TableColumnList = [

        {
            label: "id",
            prop: "id",
            align: "left"
        },
        {
            label: "所属分类",
            prop: "cid",
            minWidth: 200
        },
        {
            label: "属性类型",
            prop: "attrType",
            minWidth: 200,
            formatter: ({ attrType }) => (attrType == "0" ? "销售属性 " : "基本参数"),
        },
        {
            label: "属性名",
            prop: "attrName",
            minWidth: 200
        },

        {
            label: "是否检索",
            prop: "searchType",
            minWidth: 200,
            formatter: ({ searchType }) => (searchType == "0" ? "否 " : "是"),
        },

        {
            label: "录入方式",
            prop: "inputType",
            minWidth: 200,
            formatter: ({ inputType }) => (inputType == "0" ? "手工录入 " : "列表获取"),
        },

        {
            label: "值类型",
            prop: "valueType",
            minWidth: 200,
            formatter: ({ valueType }) => (valueType == "1" ? "单值 " : "多值"),
        },

        {
            label: "可选值",
            prop: "valueSelect",
            minWidth: 200
        },



        {
            label: "快速展示",
            prop: "showDesc",
            minWidth: 200,
            formatter: ({ showDesc }) => (showDesc == "0" ? "否 " : "是"),
        },


        {
            label: "启用状态",
            prop: "enable",
            minWidth: 200,
            formatter: ({ enable }) => (enable == "0" ? "禁用 " : "启用"),
        },
        {
            label: "创建时间",
            minWidth: 200,
            prop: "createTime",


        },



        {
            label: "备注",
            prop: "remark",
            minWidth: 200
        },


        {
            label: "操作",
            fixed: "right",
            width: 210,
            slot: "operation"
        }
    ];


    async function onSearchCategoty() {
        const result = await CategoryListTree({}); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
        if (result.success) {
            categotyList.value = result.data;
            optionsData.categotyList = result.data;
        }
    }

    function handleSelectionChange(val) {
        console.log("handleSelectionChange", val);
    }

    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }


    /**
   * 页数改变
   * @param val 
   */

    function handleSizeChange(val: number) {
        console.log(`${val} items per page`);
        onSearch();
    }

    /**
     * 页码改变
     * @param val 
     */
    function handleCurrentChange(val: number) {
        console.log(`current page: ${val}`);
        onSearch();
    }
    async function onSearch() {
        loading.value = true;
        console.log("getParameter", getParameter);
        let params = toRaw(form);
        params.pageIndex = pagination.currentPage;
        params.pageSize = pagination.pageSize;
        params.groupId = getParameter.attrGroupId;
        console.log("params", params);

        AttrList(params).then(result => {

            if (result.success) {
                dataList.value = result.data;
                pagination.total = result.total;
                pagination.pageSize = result.pageSize;
                pagination.currentPage = result.pageIndex;
            }
        }).finally(() => {
            loading.value = false;
        });



    }

    /**
     * 装载转换其他数据
     * @param treeList
     * @returns
     */
    function formatHigherDeptOptions(treeList) {
        // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
        if (!treeList || !treeList.length) return;
        const newTreeList = [];
        for (let i = 0; i < treeList.length; i++) {
            treeList[i].disabled = treeList[i].status === 0 ? true : false;
            formatHigherDeptOptions(treeList[i].children);
            newTreeList.push(treeList[i]);
        }
        return newTreeList;
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        console.log("row", row);

        addDialog({
            title: title,
            props: {
                formInline: {
                    higherOptions: formatHigherDeptOptions(cloneDeep(dataList.value)),//状态其他数据
                    dictOptionData: optionsData,
                    id: row?.id ?? null,
                    attrGroupId: getParameter.attrGroupId ?? null,
                    attrName: row?.attrName ?? null,

                    searchType: row?.searchType ?? null,

                    inputType: row?.inputType ?? null,

                    valueType: row?.valueType ?? null,

                    valueSelect: row?.valueSelect ?? null,

                    attrType: row?.attrType ?? null,

                    enable: row?.enable ?? null,

                    categoryId: row?.cid ?? null,

                    showDesc: row?.showDesc ?? null,

                    revision: row?.revision ?? null,

                    createBy: row?.createBy ?? null,

                    createTime: row?.createTime ?? null,

                    updateBy: row?.updateBy ?? null,

                    updateTime: row?.updateTime ?? null,

                    remark: row?.remark ?? null,

                    delFlag: row?.delFlag ?? null,

                    tenantId: row?.tenantId ?? null,

                }
            },
            width: "40%",
            draggable: true,
            fullscreen: deviceDetection(),
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(editForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;

                function chores(isAdd: Boolean) {
                    if (isAdd) {
                        AttrAdd(curData).then((result) => {
                            if (result.success) {
                                feedback.msgSuccess("操作成功");
                                done(); // 关闭弹框
                                onSearch(); // 刷新表格数据
                            }
                        }).catch((err) => {
                            feedback.msgError(err.message ? err.message : `操作失败`);
                        });

                    } else {
                        AttrEdit(curData).then((result) => {
                            if (result.success) {
                                feedback.msgSuccess(`操作成功`);
                                done(); // 关闭弹框
                                onSearch(); // 刷新表格数据
                            }
                        }).catch((err) => {
                            feedback.msgError(err.message ? err.message : `操作失败`);
                        });
                    }
                }

                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            chores(true)
                        } else {
                            chores(false)
                        }
                    }
                });
            }
        });
    }

    function handleDelete(row) {

        AttrDelete([row.id]).then((result) => {
            feedback.msgSuccess("操作成功")
            onSearch();
        }).catch((err) => {
            feedback.msgError(err && err.message ? err.message : "操作失败")
        });

    }

    onMounted(() => {
        console.log("getParameter", getParameter);


        onSearch();
        onSearchCategoty()
    });

    return {
        form,
        loading,
        columns,
        dataList,
        optionsData,
        /** 搜索 */
        onSearch,
        /** 重置 */
        resetForm,
        /** 新增、修改 */
        openDialog,
        /** 删除 */
        handleDelete,
        pagination,
        handleSelectionChange,
        handleSizeChange,
        handleCurrentChange,

    };
}